package book;

import constant.Constant;
import utils.AnalyzingBook;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-08-23
 * Time: 20:35
 */
public class Library {
    private Book[] books;//存储图书数组
    private int bookCount;//实际存储数量
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    public Scanner sc = new Scanner(System.in);

    //调用构造方法创建对象时直接读取文件内容
    public Library () {
        readAllBook();
    }

    public int getBookCount() {
        return bookCount;
    }

    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }

    //读取文件中内容存储到内存中
    private Book[] readAllBook () {
        Book[] allBooks = analyzingBook.readObject(Constant.ALL_BOOK_FILE_NAME);
        books = new Book[Constant.BOOK_NUM];
        if(allBooks == null) {
            return null;
        }else {
            //判断文件读取的数组大小是否大于图书馆存储大小
            int fileBookNum = allBooks.length;
            if(fileBookNum > books.length) {
                books = new Book[fileBookNum];
            }
            //将读取的数据存储到图书馆数组中
            for (int i = 0; i < fileBookNum; i++) {
                books[i] = allBooks[i];
            }
            bookCount = fileBookNum;
        }
        return books;
    }

    //将内存中数据存储到文件中
    private void writeAllBook() {
        analyzingBook.writeObject(books, Constant.ALL_BOOK_FILE_NAME);
    }

    //查找图书方法
    public void searchBook() {
        sc.nextLine();
        System.out.println("请输入你要查找的图书书名：");
        String bookName = sc.nextLine();
        Book book = search(bookName);
        if(book == null) {
            System.out.println("没有找到这本书");
        }else {
            System.out.println("找到了这本书，信息如下：");
            System.out.println(book);
        }
    }

    //根据书名查找对应的书
    public Book search(String bookName) {
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookName() == bookName) {
                return books[i];
            }
        }
        return null;
    }

    //打印所有图书
    public void displayBooks() {
        readAllBook();
        System.out.println("图书馆所有图书列表：");
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }

    //退出系统
    public void exit() {
        System.out.println("退出系统");
        System.exit(0);
    }

    //----------管理员的操作----------
    //添加图书
    public void addBook(Book book) {
        readAllBook();
        if(bookCount >= books.length) {
            System.out.println("图书馆存储已满");
            return;
        }
        //存放书
        books[bookCount] = book;
        //修改图书id
        if(bookCount == 0) {
            book.setBookId(1);
        }else {
            Book bookLast = books[bookCount - 1];
            book.setBookId(bookLast.getBookId() + 1);
        }
        bookCount++;
        //将图书写入文件
        writeAllBook();
        System.out.println("图书上架成功,书名为:" + book.getBookName());
    }
    //修改图书
    public void upDateBook(Book book) {
        writeAllBook();
        System.out.println("图书修改成功,更新后的信息为：");
        System.out.println(book);
    }

    //根据id找到对应的图书
    public Book searchBook(int bookId) {
        readAllBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId() == bookId) {
                return books[i];
            }
        }
        return null;
    }

    //下架图书
    public void removeBook(int bookId) {
        readAllBook();
        //找到删除图书对应的下标
        int removeBookNum = searchBookIndex(bookId);
        if(removeBookNum == -1) {
            System.out.println("没有找到要删除的书");
        }
        books[removeBookNum] = null;
        for (int i = removeBookNum; i < bookCount - 1; i++) {
            books[i] = books[i+1];
        }
        writeAllBook();
        System.out.println("下架图书成功");
    }

    //根据图书id找到对应下标
    public int searchBookIndex(int bookId) {
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId() == bookId) {
                return i;
            }
        }
        return -1;
    }

    //统计图书借阅次数
    public void borrowNumBook() {
        readAllBook();
        System.out.println("-----------------------");
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名: "+book.getBookName()+
                    " 借阅次数："+book.getBorrowCount());
        }
        System.out.println("-----------------------");
    }

    //查看最受欢迎的前n本书
    public void popularBook(int n) {
        writeAllBook();
        Book[] book1 = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            book1[i] = books[i];
        }
        Arrays.sort(book1);
        Book[] book2 = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            book2[i] = book1[i];
        }
        for (int i = 0; i < n; i++) {
            System.out.println(book2[i]);
        }
    }

    //查看库存状态
    public void numBook() {
        readAllBook();
        System.out.println("--------------------------");
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String s = book.getIsBorrowed()?"已借出":"未借出";
            System.out.println("书名：" + book.getBookName() + " 借阅状况：" + s);
        }
        System.out.println("--------------------------");
    }

    //移除上架超过一年的书
    public void removeOneBook() {
        readAllBook();
        //获取当前时间的时间戳
        long currentTimestamp = System.currentTimeMillis();
        //将当前时间戳转换为LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean isRemove = false;
        for (int i = 0; i < bookCount; i++) {
            LocalDate localDate = books[i].getShelfDate();
            //计算两个⽇期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(localDate,
                    currentDate);
            if(yearsBetween >= 1) {
                System.out.println(books[i].getBookName() + " 已经上架超过一年，是否移除(y/n)：");
                String s = sc.nextLine();
                if(s.equals("y")) {
                    removeBook(books[i].getBookId());
                    bookCount--;
                    i--;
                }
                isRemove = true;
            }
        }
        if(!isRemove) {
            System.out.println("没有上架超过一年的书");
        }
        writeAllBook();
    }

    //----------普通用户的操作----------
    //借书
    public void borrowBook(int bookId) {
        readAllBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId() == bookId) {
                books[i].setIsBorrowed(true);
                books[i].borrowBook();
            }
        }
        writeAllBook();
    }

    //还书
    public void returnBook(int bookId) {
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId() == bookId) {
                books[i].setIsBorrowed(false);
            }
        }
        writeAllBook();
    }

    /*
    1,三国演义,罗贯中,名著,2025,false,1,2025-08-26
2,水浒传,韩进,名著,2025,false,2,2025-08-26
3,活着,余华,小说,2035,false,3,2023-08-26
     */
}
